﻿using MonitorPrism_Practice.Model;
using MonitorPrism_Practice.Mvvm;
using MonitorPrism_Practice.Services;
using MonitorPrism_Practice.ViewModel;
using MonitorPrism_Practice.Views;
using MonitorPrism_Practice.Views.SettingConfig;
using Newtonsoft.Json.Linq;
using SCADALight.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;

namespace MonitorPrism_Practice.ViewModels
{
    public class InterfaceReciveDataViewModel : BindableBase, IViewLoadedAndUnloadedAware
    {
        Window ViewWindow;
        public IPlcService _plcService;
        private readonly IUndoRedoManager _undoManager;
        public InterfacePlotViewModel _interfacePlotViewModel;
        private LogEventService _logEventService;
        private readonly Dictionary<string, InterfaceReciveDataModel> _itemsByName;
        private IEventAggregator _aggregator { get; }

        private ObservableCollection<InterfaceReciveDataModel> _items = new ObservableCollection<InterfaceReciveDataModel>()
        {
            new InterfaceReciveDataModel(){Name = "温度",Address = "DBD82.DBDW38",DbIndex = 82,DbDataIndex = 38,DataType = S7.Net.VarType.Real},
            new InterfaceReciveDataModel(){Name = "功率",Address = "DBD63.DBDW154",DbIndex = 63,DbDataIndex = 154,DataType = S7.Net.VarType.Real},
            new InterfaceReciveDataModel(){Name = "目标温度",Address = "DBD63.DBDW24",DbIndex = 63,DbDataIndex = 24, DataType = S7.Net.VarType.Real},
            new InterfaceReciveDataModel(){Name = "功率上限",Address = "DBD63.DBDW88",DbIndex = 63,DbDataIndex = 88,DataType = S7.Net.VarType.Real},
            new InterfaceReciveDataModel(){Name = "积分隔离",Address = "DBD63.DBDW114",DbIndex = 63,DbDataIndex = 114, DataType = S7.Net.VarType.Real},
            new InterfaceReciveDataModel(){Name = "Kp",Address = "DBD63.DBDW0",DbIndex = 63,DbDataIndex = 0, DataType = S7.Net.VarType.Real},
            new InterfaceReciveDataModel(){Name = "Ki",Address = "DBD63.DBDW4",DbIndex = 63,DbDataIndex = 4, DataType = S7.Net.VarType.Real},
            new InterfaceReciveDataModel(){Name = "Kd",Address = "DBD63.DBDW8",DbIndex = 63,DbDataIndex = 8, DataType = S7.Net.VarType.Real},
        };
        public ObservableCollection<InterfaceReciveDataModel> Items
        {
            get { return _items; }
            set
            {
                SetProperty(ref _items, value);
            }
        }

        private ICommand _openAddDadaViewCommand;
        public ICommand OpenAddDadaViewCommand
        {
            get
            {
                return this._openAddDadaViewCommand ?? (this._openAddDadaViewCommand = new DelegateCommand(() => { AddReciveDataView window = new AddReciveDataView(); window.Show(); }));
            }
        }

        private ICommand _deleteItemCommand;
        public ICommand DeleteItemCommand
        {
            get
            {
                return this._deleteItemCommand ?? (this._deleteItemCommand = new DelegateCommand<InterfaceReciveDataModel>((item) =>
                {
                    MessageBoxResult result = System.Windows.MessageBox.Show(
                     $"确定要删除 {item.Name} 吗?",
                        "确认删除",
                         MessageBoxButton.YesNo,
                         MessageBoxImage.Question);
                    DeleteItem(item);
                }));
            }
        }

        private ICommand _undoCommand;
        public ICommand UndoCommand
        {
            get
            {
                return this._undoCommand ?? (this._undoCommand = new DelegateCommand(() => { Undo(); }));
            }
        }

        private ICommand _redoCommand;
        public ICommand RedoCommand
        {
            get
            {
                return this._redoCommand ?? (this._redoCommand = new DelegateCommand(() => { Redo(); }));
            }
        }
        private ICommand _clearUndoRedoCommand;
        public ICommand ClearUndoRedoCommand
        {
            get
            {
                return this._clearUndoRedoCommand ?? (this._clearUndoRedoCommand = new DelegateCommand(() => _undoManager.Clear()));
            }
        }
        public void DeleteItem(InterfaceReciveDataModel item)
        {
            int index = Items.IndexOf(item);
            if (index >= 0)
            {
                _undoManager.Execute(
                () => Items.RemoveAt(index),
                () => Items.Insert(index, item),  // 撤销删除
                $"删除 {item.Name}"  // 操作描述
            );
            }
        }
        public void Additem(InterfaceReciveDataModel item)
        {
            int index = Items.Count;
            if (index >= 0)
            {
                _undoManager.Execute(
                () => Items.Add(item),
                () => Items.RemoveAt(index),  // 撤销删除
                $"删除 {item.Name}"  // 操作描述
            );
            }
        }
        private void Undo() => _undoManager.Undo();//撤销
        private void Redo() => _undoManager.Redo();//重做
        public InterfaceReciveDataViewModel(IPlcService plcService,
                                    InterfacePlotViewModel interfacePlotViewModel,
                                    IUndoRedoManager undoManager)
        {
            _undoManager = undoManager;
            _plcService = plcService;
            _interfacePlotViewModel = interfacePlotViewModel;
            _aggregator = ContainerLocator.Current.Resolve<IEventAggregator>();
            _aggregator.GetEvent<ReciveDataEvent>().Subscribe(Additem);
            _itemsByName = _items.ToDictionary(item => item.Name);
            _logEventService = ContainerLocator.Current.Resolve<LogEventService>();
        }




        public async void OnLoaded(object sender, RoutedEventArgs e)
        {

            ViewWindow = sender as Window;
            await Task.Run(async () =>
              {
                  try
                  {
                      while (true)
                      {
                          if (_plcService.IsConnected)
                          {

                              foreach (var item in Items)
                              {
                                  _plcService.ReadData(item);
                              }
                              if (_itemsByName.TryGetValue("温度", out var temperature) &&
                                   _itemsByName.TryGetValue("目标温度", out var targetTemperature) &&
                                   _itemsByName.TryGetValue("功率", out var power))
                              {
                                  _interfacePlotViewModel.Values = [Convert.ToDouble(temperature.Value), Convert.ToDouble(targetTemperature.Value), Convert.ToDouble(power.Value) * 20];

                              }
                          }
                          await Task.Delay(150);
                      }
                  }
                  catch (Exception ex)
                  {
                      _logEventService.AddItem(new LogEventModel() { Message = ex.Message });


                  }

              });
        }


        public void OnUnloaded(object sender, RoutedEventArgs e)
        {
            _undoManager.Clear();
        }
    }
}
